package com.lej.dataservice.club.http.interceptor

import android.provider.Settings
import com.lej.core.BuildConfig
import com.lej.core.base.app
import com.lej.core.common.*
import com.lej.core.utils.KV
import com.lej.dataservice.club.http.base.AES
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 添加请求头token
 */
class HeaderInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val token = PCacheInfo.token
        val request = chain.request().newBuilder()
            .apply { if (token.isNotEmpty()) header("Authorization", "Bearer $token") }
            .header(OS, "1")//1代表Android设备
            .header(VERSION, BuildConfig.VERSION_CODE.toString())
            .header(LOCATION, KV.kv.getString(LOCATION))
            .header(HTTP_UUID, PCacheInfo.uuid)
            .header(OAID, getCid())
            .build()
        return chain.proceed(request)
    }

    companion object {
        private var entry: String = ""

        private fun getCid(): String {
            if (entry.isNotEmpty()) return entry
            var cid = PCacheInfo.oaid
            if (cid.isBlank() || cid == "00000000-0000-0000-0000-000000000000") {
                cid = runCatching {
                    Settings.System.getString(
                        app.contentResolver,
                        Settings.System.ANDROID_ID
                    )
                }.getOrElse { "" }
            }
            if (cid.isBlank()) cid = PCacheInfo.clientId

            if (cid.isBlank()) return entry
            entry = runCatching { AES.encryptToBase64(cid) }.getOrElse { "" }
            return entry
        }
    }
}
